package com.caisejingyu.whales.common.utils;

import android.content.Context;
import android.os.Build;
import android.text.TextUtils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

/**
 * 各种码生成器
 *
 */
@SuppressWarnings({"WeakerAccess", "unused"})
public class CodeGenerator {

    public static String generateUniqueDeviceCode(Context context) {
        return generateUniqueDeviceCode(null, context);
    }

    /** 生成设备唯一码 */
    public static String generateUniqueDeviceCode(String androidId, Context context) {
        if (TextUtils.isEmpty(androidId)) {
            androidId = DeviceUtil.getAndroidId(context);
        }
        String macAddress = DeviceUtil.getMacAddress(context);
        String deviceCode = androidId + getShortId() + macAddress;
        StringBuilder digestDeviceCodeSb = new StringBuilder();
        // MD5加密
        MessageDigest messageDigest;
        try {
            messageDigest = MessageDigest.getInstance("MD5");
            messageDigest.update(deviceCode.getBytes(), 0, deviceCode.length());
            byte digestBytes[] = messageDigest.digest();
            for (byte digestByte : digestBytes) {
                int b = (0xFF & digestByte);
                if (b <= 0xF) {
                    digestDeviceCodeSb.append("0");
                }
                digestDeviceCodeSb.append(Integer.toHexString(b));
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return digestDeviceCodeSb.toString().toUpperCase();
    }

    private static String getShortId() {
        return "35" + Build.BOARD.length() % 10 +
                Build.BRAND.length() % 10 +
                Build.CPU_ABI.length() % 10 +
                Build.DEVICE.length() % 10 +
                Build.DISPLAY.length() % 10 +
                Build.HOST.length() % 10 +
                Build.ID.length() % 10 +
                Build.MANUFACTURER.length() % 10 +
                Build.MODEL.length() % 10 +
                Build.PRODUCT.length() % 10 +
                Build.TAGS.length() % 10 +
                Build.TYPE.length() % 10 +
                Build.USER.length() % 10;
    }

    public static String generateUuid() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }
}
